<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportEmployee">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" align="center">
            <template #default="{row}">
              <img v-imagerror="require('@/assets/common/bigUserHeader.png')" :src="row.staffPhoto" alt="" style="border-radius: 50%; width: 100px; height: 100px; padding: 10px" @click="showQrCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="employeeFormatter" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template slot-scope="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState" />
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRole(row.id)">角色</el-button>
              <el-button :disabled="!checkPermission('POINT-USER-DELETE')" type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :total="total" :page-size="query.size" @current-change="handleCurrentChange" />
        </el-row>
      </el-card>
    </div>
    <add-employee :show-dialog.sync="showDialog" />
    <!-- 对话框 -->
    <el-dialog
      title="二维码"
      :visible.sync="dialogVisible"
      width="15%"
    >
      <canvas ref="abc" />
    </el-dialog>

    <assign-role v-if="showRoleDialogVisible" :show-role-dialog.sync="showRoleDialogVisible" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
import qrCode from 'qrcode'
import AssignRole from './components/assign-role'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      query: {
        page: 1,
        size: 10
      },
      list: [],
      total: 0,
      showDialog: false,
      dialogVisible: false,
      showRoleDialogVisible: false,
      userId: null
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      const res = await getEmployeeList(this.query)
      this.list = res.rows
      this.total = res.total
      console.log(res)
    },
    handleCurrentChange(current) {
      this.query.page = current
      this.getEmployeeList()
    },
    employeeFormatter(row, column, cellValue, index) {
      // find根据条件找到符合的第一项，返回这一项
      const res = EmployeeEnum.hireType.find(item => item.id === cellValue)
      console.log(res)
      if (res) {
        return res.value
      } else {
        return '未知的类型'
      }
    },
    async deleteEmployee(id) {
      try {
        await this.$confirm('您确定删除该员工吗')
        await delEmployee(id)
        this.getEmployeeList()
        this.$message.success('删除成功')
      } catch (err) {
        this.$message.error('取消删除')
      }
    },
    exportEmployee() {
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeeList({ page: 1, size: this.total })
        const data = []// 存最终处理好的结果

        rows.forEach(item => {
          const res = EmployeeEnum.hireType.find(item1 => item1.id === item.formOfEmployment)
          if (res) {
            item.formOfEmployment = res.value
          } else {
            item.formOfEmployment = '未知'
          }
          data.push([
            item.mobile,
            item.username,
            formatDate(item.timeOfEntry),
            item.formOfEmployment,
            formatDate(item.correctionTime),
            item.workNumber,
            item.departmentName
          ])
        })
        console.log(data)
        excel.export_json_to_excel({
          header: ['手机号', '姓名', '入职日期', '聘用形式', '转正日期', '工号', '部门'], // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx', // 非必填
          multiHeader: [['手机号', '主要信息', '', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2']
        })
      })
    },
    // qr 二维码
    showQrCode(url) {
      if (url) {
        this.dialogVisible = true
        this.$nextTick(() => {
          console.log(this.$refs.abc)
          qrCode.toCanvas(this.$refs.abc, url)
        })
      } else {
        this.$message.error('当前用户还没有上传头像')
      }
    },
    showRole(id) {
      // console.log(id)
      this.userId = id
      this.showRoleDialogVisible = true
    }
  }
}
</script>

<style>

</style>
